import 'package:flutter/material.dart';
// 导入swiper 组件
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:secend_flutter/bean/home_common_model_bean.dart';
import 'package:secend_flutter/bean/home_grid_nav_model_bean.dart';
import 'package:secend_flutter/bean/home_model_bean.dart';
import 'package:secend_flutter/bean/home_sales_box_model_bean.dart';
import 'package:secend_flutter/bottom_bar/speak_page.dart';
import 'package:secend_flutter/dao/home_dao.dart';
import 'package:secend_flutter/dao/tao_ean.dart';
import 'package:secend_flutter/define_widget/grid_nav.dart';
import 'package:secend_flutter/define_widget/loading_data_home.dart';
import 'package:secend_flutter/define_widget/sale_box.dart';
import 'package:secend_flutter/define_widget/webview_widget.dart';
import 'package:secend_flutter/bottom_bar/search_item_page.dart';
import 'package:secend_flutter/define_widget/appbar_search_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:easy_refresh/easy_refresh.dart';
const APPBAR_SCROLL_OFFSET = 200;

class HomePage extends StatefulWidget {

  const HomePage({Key? key}) : super(key: key);

  // 重写Create State 方法
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<CommonBean> bannerList = [];
  List<CommonBean> navList = [];
  GridNavBean? gridNavBean;
  List<CommonBean> subNavList = [];
  SalesBoxBean? salesBoxBean;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _handleRefresh();
    // _sharedPreference();
  }
   _sharedPreference() async{
    final share =await SharedPreferences.getInstance();
    share.setString('key', '123');
    // share.remove('key');
  }

  Future<void> _handleRefresh() async {
    // final share =await SharedPreferences.getInstance();
    // print('${share.getString('key')??'0'}');
    try {
      HomeBean homeModelBean = await HomeDao.fetch();
      setState(() {
        bannerList = homeModelBean.bannerList;
        navList = homeModelBean.localNavList;
        gridNavBean = homeModelBean.gridNav;
        subNavList = homeModelBean.subNavList;
        salesBoxBean = homeModelBean.salesBox;
        _loading = false;
      });
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return;
  }

  _onScroll(offset) {
    //offset滚动距离
    double alpha = offset / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
    print('透明度' + appBarAlpha.toString());
  }

  //定义一个AppBar 的透明度默认值
  double appBarAlpha = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // MediaQuery.removePadding 移除顶部的 padding
      // 使用Stack 的作用就是让AppBar 叠加在上面
      body: LoadingProgress(
          isLoading: _loading,
          child: EasyRefresh(
              child: Stack(
                children: [
                  MediaQuery.removePadding(
                    removeTop: true,
                    context: context,
                    // 监听列表的滚动
                    child: NotificationListener(
                      // 滚动的回调
                      onNotification: (scrollNotifation) {
                        // 判断ListView滚动的效果
                        if (scrollNotifation is ScrollUpdateNotification &&
                            scrollNotifation.depth == 0) {
                          // 滚动且是列表滚动的的的时候
                          _onScroll(scrollNotifation.metrics.pixels);
                        }
                        return false;
                      },
                      child: ListView(
                        children: <Widget>[
                          Column(
                            children: <Widget>[
                              SizedBox(
                                height: ScreenUtil().setHeight(330),
                                width: ScreenUtil().setWidth(750),
                                child: Swiper(
                                  onTap: (index){
                                    Tiaboon.push(
                                        context,
                                        MyWebView(
                                        url: bannerList[index].url,
                                        title: bannerList[index].title,
                                        hideAppBar:
                                        bannerList[index].hideAppBar,
                                    ));
                                  },
                                  itemCount: bannerList.length,
                                  itemBuilder: (context, index) {
                                    return Image.network(
                                        bannerList[index].icon!,
                                        fit: BoxFit.fill,
                                      );
                                  },
                                  pagination: const SwiperPagination(),
                                  autoplay: true,
                                ),
                              ),
                              Container(
                                padding: const EdgeInsets.only(top: 7,left: 14,right: 14,bottom: 7),
                                height: ScreenUtil().setHeight(130),
                                width: ScreenUtil().setWidth(750),
                                decoration: BoxDecoration(
                                    color: Colors.white,
                                    border: Border.all(
                                        color: Colors.white, width: 5),
                                    // 设置边框
                                    borderRadius: const BorderRadius.all(
                                        Radius.circular(10))),
                                // 设置正圆角
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: _navgaptors(),
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
                                child: GridNavitor(
                                  gridNavBean: gridNavBean,
                                ),
                              ),
                              Container(
                                margin: const EdgeInsets.only(top: 5),
                                padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
                                child: PhysicalModel(
                                  borderRadius: BorderRadius.circular(5),
                                  color: Colors.white,
                                  clipBehavior: Clip.antiAlias,
                                  child: _subItems(),
                                ),
                              ),
                              Padding(
                                  padding:
                                      const EdgeInsets.fromLTRB(7, 0, 7, 4),
                                  child: SalesBox(
                                      salesBoxBean: salesBoxBean == null
                                          ? null
                                          : salesBoxBean!))
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                  _appbar()
                ],
              ),
              onLoad: (){},
              onRefresh: _handleRefresh)),
    );
  }

  _appbar() {
    return Column(
      children: [
        Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
                colors: [Color(0x66000000), Colors.transparent],
                end: Alignment.topCenter,
                begin: Alignment.bottomCenter),
          ),
          child: Container(
            padding: const EdgeInsets.only(top: 25),
            height: 80,
            decoration: BoxDecoration(
                color:
                    Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255)),
            child: AppBarSearch(
              hideLeftS: true,
              searchBarTypeS: appBarAlpha > 0.2
                  ? SearchBarTypeS.homeLight
                  : SearchBarTypeS.home,
              hintS: '',
              defaultTextS: "网红打卡地 景点 酒店 美食",
              leftButtonOnClick: () {},
              speakOnClick: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => SpeakPage()));
              },
              inputBoxClick: () {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const SearchPage(
                              hideLeft: false,
                              hint: '网红 ',
                            )));
              },
            ),
          ),
        ),
        Container(
          height: appBarAlpha > 0.2 ? 0.5 : 0,
          decoration: const BoxDecoration(boxShadow: [
            BoxShadow(
                color: Colors.black12, blurRadius: 0.5), // 高斯的标准偏差与盒子的形状卷积。
          ]),
        )
      ],
    );
  }

  _navgaptors() {
    List<Widget> items = [];
    navList.map((e) {
      items.add(_nagatoritem(e));
    }).toList();
    return items;
  }

  Widget _nagatoritem(CommonBean e) {
    return GestureDetector(
      onTap: () {
        Tiaboon.push(
            context,
            MyWebView(
              url: e.url,
              statusBarColor: e.statusBarColor,
              hideAppBar: e.hideAppBar,
            ));
      },
      child: Column(
        children: [
          Image.network(
            e.icon!,
            height: 30,
            width: 42,
          ),
          Text(
            e.title!,
            style: const TextStyle(color: Colors.black, fontSize: 14),
          ),
        ],
      ),
    );
  }

  _subItems() {
    List<Widget> items = [];
    if (subNavList == null) {
      return items;
    }
    subNavList.forEach((element) {
      items.add(_subItem(element));
    });
    int num = (subNavList.length / 2 + 0.5).toInt();

    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: items.sublist(0, num),
        ),
        Container(
          padding: const EdgeInsets.only(top: 10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: items.sublist(num, subNavList.length),
          ),
        )
      ],
    );
  }

  Widget _subItem(CommonBean value) {
    return Expanded(
      child: GestureDetector(
        onTap: () {
          Tiaboon.push(
              context,
              MyWebView(
                url: value.url,
                statusBarColor: value.statusBarColor,
                hideAppBar: value.hideAppBar,
              ));
        },
        child: Column(
          children: [
            Image.network(
              value.icon!,
              width: 18,
              height: 18,
            ),
            Padding(
              padding: const EdgeInsets.only(top: 3),
              child: Text(
                value.title!,
                style: const TextStyle(fontSize: 13),
              ),
            )
          ],
        ),
      ),
      flex: 1,
    );
  }
}
